import mongoose from "mongoose";
import { genIdFromCppCode } from "../utils.js";

const TranspileRecordSchema = new mongoose.Schema({
    // id是cpp转汇编之后的的sha1值
    id: { type: String, required: true, unique: true },
    cpp: { type: String, required: true },
    rust: { type: String, required: false },
    is_pass: { type: Boolean, default: false },
    created: {
        type: Number
    },
    updated: {
        type: Number
    }
},
    {
        timestamps: { createdAt: 'created', updatedAt: 'updated' },
    });

const TranspileRecordModle = mongoose.model('transpile_records', TranspileRecordSchema);


export async function createOrUpdate(cpp, rust, is_pass = true) {
    const id = await genIdFromCppCode(cpp);

    const record = await findById(id);
    if (!record) {
        console.log(`创建记录，${id},转译结果:${is_pass}`);
        return TranspileRecordModle.create({ id, cpp, rust, is_pass });
    }
    //有记录&未pass并且本次对比成功的（参数is_pass=true）,将对比通过的记录更新，否则不更新
    if (!record.is_pass && is_pass) {
        console.log(`数据库有转译失败记录${id}，更新为转译成功`);
        return TranspileRecordModle.findByIdAndUpdate(
            { id },
            { rust, cpp, is_pass }
        ).exec()
    }


    // else {
    //     // console.log('有记录, 什么都不做');
    //     // return TranspileRecordModle.findOneAndUpdate(
    //     //     { id },
    //     //     { rust, cpp, is_pass: true },
    //     //     { upsert: true, new: true }
    //     // ).exec();
    // }
}




export function findById(id) {
    if (!id) return null;
    return TranspileRecordModle.findOne({ id }).exec();
}

export function findByIsPass(is_pass) {
    return TranspileRecordModle.find({ is_pass }).exec();
}

export default {
    findByIsPass,
    findById,
    createOrUpdate
}